// pages/phonelist/phonelist.js
const { phoneApi } = require('../../utils/api');

// 防抖函数
function debounce(fn, delay = 300) {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

Page({
  data: {
    phoneList: [],
    searchValue: '',
    pageNum: 1,
    pageSize: 20,
    hasMore: true,
    loading: false,
    searching: false
  },

  onLoad: function (options) {
    // 初始化防抖搜索函数
    this.debouncedSearch = debounce(() => {
      this.loadPhoneList(true);
    });
    this.loadPhoneList();
  },

  // 加载手机列表数据
  loadPhoneList: function(refresh = false) {
    if (this.data.loading) return;
    
    if (refresh) {
      this.setData({
        pageNum: 1,
        hasMore: true,
        phoneList: [],
        searching: true
      });
    }

    if (!this.data.hasMore) return;
    
    this.setData({ loading: true });
    
    const params = {
      pageNum: this.data.pageNum,
      pageSize: this.data.pageSize,
      name: this.data.searchValue.trim()
    };
    
    phoneApi.getPhoneList(params).then(data => {
      // 处理数据
      let list = this.data.phoneList;
      if (refresh) {
        list = data.list || [];
      } else {
        list = list.concat(data.list || []);
      }
      
      this.setData({
        phoneList: list,
        hasMore: data.hasNextPage,
        pageNum: this.data.pageNum + 1,
        loading: false,
        searching: false
      });
    }).catch(err => {
      this.setData({ 
        loading: false,
        searching: false
      });
      console.error('获取手机列表失败', err);
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      });
    });
  },

  // 下拉刷新
  onPullDownRefresh: function() {
    this.loadPhoneList(true);
    wx.stopPullDownRefresh();
  },
  
  // 上拉加载更多
  onReachBottom: function() {
    this.loadPhoneList();
  },

  // 输入搜索内容
  onInput: function(e) {
    const value = e.detail.value;
    this.setData({ searchValue: value });
    if (value) {
      this.debouncedSearch();
    }
  },

  // 清空搜索内容
  onClear: function() {
    this.setData({
      searchValue: ''
    });
    this.loadPhoneList(true);
  },

  // 搜索按钮点击
  onSearch: function() {
    if (!this.data.searchValue.trim()) {
      return wx.showToast({
        title: '请输入搜索内容',
        icon: 'none'
      });
    }
    this.loadPhoneList(true);
  },

  // 前往手机详情页
  goToPhoneDetail: function(e) {
    const phoneId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/phonedetail/phonedetail?id=${phoneId}`
    });
  }
}) 